package com.xmtlxx.sacw.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.sacw.domain.DisposalInfo;
import com.xmtlxx.sacw.domain.DisposalPro;
import com.xmtlxx.sacw.domain.bo.DisposalConfirmBo;
import com.xmtlxx.sacw.domain.bo.DisposalRegisterBo;
import com.xmtlxx.sacw.domain.bo.DisposalRegisteredBo;
import com.xmtlxx.sacw.domain.vo.DisposalRegisteredInfoVo;
import com.xmtlxx.sacw.mapper.DisposalInfoMapper;
import com.xmtlxx.sacw.mapper.DisposalProMapper;
import com.xmtlxx.sacw.mapper.SacwMapper;
import com.xmtlxx.sacw.service.IDisposalService;
import com.xmtlxx.sacw.service.base.SacwBaseService;
import com.xmtlxx.system.enums.OssBuss;
import com.xmtlxx.system.mapper.SysOssMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 处置service业务实现
 *
 * @author hergreen
 * @date 2024/07/19 10:37
 **/
@Slf4j
@RequiredArgsConstructor
@Service
public class DisposalServiceImpl extends SacwBaseService implements IDisposalService {

    private final SacwMapper sacwMapper;

    private final DisposalInfoMapper disposalInfoMapper;

    private final DisposalProMapper disposalProMapper;

    private final SysOssMapper sysOssMapper;


    private QueryWrapper<Object> getDisposalConfirmQueryBuild(DisposalConfirmBo bo) {

        return new QueryWrapper<>().func(i -> {
            //pro_base office id in user data scopes
            i.in("PB.OFFICE_ID", getUserDataScopes());
            i.eq(StrUtil.isNotBlank(bo.getDisposalOpinion()), "PDOI.OPINION", bo.getDisposalOpinion());
            if (bo.getCenterPro() != null) {
                if (bo.getCenterPro()) {
                    i.isNotNull("I.ID");
                    i.eq(StrUtil.isNotBlank(bo.getStoreName()), "R.NAME", bo.getStoreName());
                } else {
                    i.isNull("I.ID");
                }
            }
            switch (bo.getStatus()) {
                case "1":
                    // not register
                    i.eq("S.TRANSFER_STATUS", "0");
                    break;
                case "2":
                    // registered and unconfirmed
                    i.eq("S.TRANSFER_STATUS", "2");
                    i.isNull("T.PNO");
                    break;
                case "3":
                    // registered and confirmed
                    i.eq("S.TRANSFER_STATUS", "2");
                    i.isNotNull("T.PNO");
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    public TableDataInfo<DisposalConfirmBo> getDisposalConfirmPage(PageQuery pageQuery, DisposalConfirmBo bo) {

        return TableDataInfo.build(sacwMapper.getDisposalConfirmPage(pageQuery.build(), getDisposalConfirmQueryBuild(bo)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disposalRegister(DisposalRegisterBo bo) {

        bo.getDisposalInfo().setDeptId(LoginHelper.getDeptId());
        //销毁时，处置时间记录销毁时间
        if(bo.getDisposalInfo().getDisposalStat().equals("6")) {
            bo.getDisposalInfo().setDealDate(bo.getDisposalInfo().getDestoryDate());
        }

        if (disposalInfoMapper.insert(bo.getDisposalInfo()) == 0) {
            throw new RuntimeException("保存登记信息失败");
        }

        if (!disposalProMapper.insertBatch(bo.getProList())) {
            throw new RuntimeException("保存登记信息失败");
        }

        //update oss info
        sysOssMapper.updateBatchBussAndObjIdById(bo.getDisposalInfo().getOss(),
                OssBuss.DISPOSAL_REGISTER, bo.getDisposalInfo().getId());

    }

    private QueryWrapper<Object> getDisposalRegisteredQueryBuild(DisposalRegisteredBo bo) {

        String existSql = "SELECT 1 FROM S_DISPOSAL_PRO WHERE PRO_NO = '{}' AND DI.ID = DISPOSAL_ID AND DEL_FLAG = 0";

        return new QueryWrapper<>().func(i -> {
            i.eq("DI.DEPT_ID", LoginHelper.getDeptId());
            i.eq(bo.getDisposalStat() != null, "DI.DISPOSAL_STAT", bo.getDisposalStat());
            i.eq(StrUtil.isNotBlank(bo.getRegion()), "D.REGION", bo.getRegion());
            i.exists(StrUtil.isNotBlank(bo.getProNo()), StrUtil.format(existSql, bo.getProNo()));
        });
    }

    @Override
    public TableDataInfo<DisposalRegisteredBo> getDisposalRegisteredPage(PageQuery pageQuery, DisposalRegisteredBo bo) {

        return TableDataInfo.build(disposalInfoMapper.getDisposalRegisteredList(pageQuery.build(),
                getDisposalRegisteredQueryBuild(bo)));
    }

    @Override
    public DisposalRegisteredInfoVo getDisposalRegisteredInfo(String id) {

        return disposalInfoMapper.getDisposalRegisteredInfo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDisposalRegistered(String id) {

        if (disposalInfoMapper.updateById(new DisposalInfo(id)) == 0) {
            throw new ServiceException("删除信息失败");
        }

        LambdaUpdateWrapper<DisposalPro> wrapper = new LambdaUpdateWrapper<DisposalPro>()
                .eq(DisposalPro::getDisposalId, id).set(DisposalPro::getDelFlag, 1);
        if (disposalProMapper.update(new DisposalPro(), wrapper) == 0) {
            throw new ServiceException("删除物品失败");
        }
    }

    @Override
    public boolean updateInfo(DisposalInfo disposalInfo) {

        return disposalInfoMapper.updateById(disposalInfo) > 0;
    }

    @Override
    public boolean addPro(List<DisposalPro> disposalProList) {

        return disposalProMapper.insertBatch(disposalProList);
    }

    @Override
    public boolean deletePro(String id) {

        return disposalProMapper.updateById(new DisposalPro(id)) > 0;
    }

    @Override
    public void uploadExcel(List<List<String>> data) {
        DisposalRegisterBo bo  = new DisposalRegisterBo();
        bo.setDisposalInfo(new DisposalInfo());
        List<DisposalPro> list = new ArrayList<>();
        bo.setProList(list);
        bo.getDisposalInfo().setDisposalStat("5");
        Double dealPriceAll = 0.0;
        Double floorPriceAll = 0.0;
        for(int i = 0; i < data.size(); i++) {
            if(i > 1){
                List<String> disInfo = data.get(i);
                DisposalPro disPro =  new DisposalPro();
                if(disInfo.get(5) != null){
                    floorPriceAll = floorPriceAll + Double.parseDouble(disInfo.get(5));
                }
                if(disInfo.get(8) != null){
                    Double dealPrice = Math.round(Double.parseDouble(disInfo.get(8)) * 100)/100.0;
                    disPro.setDisposalAmount(BigDecimal.valueOf(dealPrice));
                }

                //查询taskId
                if(disInfo.get(1) != null){
                    String taskId = disposalProMapper.getTaskIdByTaskNo(disInfo.get(1));
                    disPro.setTaskId(taskId);
                }

                if(disInfo.get(2) != null){
                    //查询物品是否已存在
                    String id = disposalProMapper.getDisposalProIdByProNo(disInfo.get(2));
                    if(id != null){
                        disposalProMapper.deleteById(id);
                    }
                    disPro.setProNo(disInfo.get(2));
                }
                if(disInfo.get(4) != null){
                    int num = (int) Double.parseDouble(disInfo.get(4));
                    disPro.setDisposalNumber(Long.parseLong(num+""));
                }
                bo.getProList().add(disPro);
            }

        }
        dealPriceAll = Math.round(Double.parseDouble(data.get(2).get(7)) * 100)/100.0;
        floorPriceAll = Math.round(Double.parseDouble(data.get(2).get(6)) * 100)/100.0;
        if(data.get(2).get(10) != null){
            String dealDate = data.get(2).get(10);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = formatter.parse(dealDate);
                bo.getDisposalInfo().setDealDate(date);
            } catch (ParseException e) {
                System.out.println("日期格式解析错误: " + e.getMessage());
            }
        }
        bo.getDisposalInfo().setDealPrice(BigDecimal.valueOf(dealPriceAll));
        bo.getDisposalInfo().setFloorPrice(BigDecimal.valueOf(floorPriceAll));
        bo.getDisposalInfo().setDeptId(LoginHelper.getDeptId());

        if (disposalInfoMapper.insert(bo.getDisposalInfo()) == 0) {
            throw new RuntimeException("保存登记信息失败");
        }
        if (!disposalProMapper.insertBatch(bo.getProList())) {
            throw new RuntimeException("保存登记信息失败");
        }

    }
}

